<?php

namespace App\Controllers;

use App\Models\RegionModel;

class Opi extends BaseController
{

    public function __construct(...$params)
    {

    }

    /**
     * 验证码
     */
    public function captcha()
    {
        $captchaLib = new \App\Libraries\Captcha();
        $height = $this->request->getGet('height');
        $width = $this->request->getGet('width');
        $code = $captchaLib->create($width, $height);
        $this->session->set('amscaptcha', $code);
        exit();
    }

    //获取城市联动
    public function get_region()
    {
        if (IS_POST) {
            $type = $this->request->getPost('type');
            $pid = $this->request->getPost('pid');
            if ($type) {
                ams_clean_xss($type);
            } elseif ($pid) {
                ams_clean_xss($pid);
            }

            if (!$type || !in_array($type, ['province', 'city', 'area'])) {
                $this->_json(1, '参数错误');
            }

            $regionModel = new RegionModel();
            $cache = $this->cache->get($type);
            if (!$cache) {
                $rt = $regionModel->cache_data();
                $cache = $rt['data'];
            }
            if ($pid) {
                $data = isset($cache[$pid]) ? $cache[$pid] : [];
            } else {
                $data = $cache;
            }

            $this->_json(0, 'OK', $data);
        }

    }

    public function downFile($filepath)
    {
        if (!is_file($filepath) && is_readable($filepath)) {
            return false;
        }

        //获取文件的扩展名
        $fileext = strtolower(pathinfo($filepath, PATHINFO_EXTENSION));
        //设置脚本的最大执行时间，设置为0则无时间限制
        set_time_limit(0);
        //通过header()发送头信息
        //因为不知道文件是什么类型的，告诉浏览器输出的是字节流
        header('Content-Description:File Transfer');
        header('Content-Type:application/octet-stream');
        header('Content-Transfer-Encoding:binary');
        //告诉浏览器返回的文件大小类型是字节
        header('Accept-Ranges:bytes');
        header('Expires:0');
        header('Cache-Control:must-revalidate');
        header('Pragma:public');
        //获得文件大小
        $filesize = filesize($filepath);
        //告诉浏览器返回的文件大小
        header('Accept-Length:' . $filesize);
        //告诉浏览器文件作为附件处理并且设定最终下载完成的文件名称
        header("Content-Disposition:attachment;filename=" . basename($filepath));

        //针对大文件，规定每次读取文件的字节数为4096字节，直接输出数据
        $read_buffer = 4096;
        $handle = fopen($filepath, 'rb');
        //总的缓冲的字节数
        $sum_buffer = 0;
        //只要没到文件尾，就一直读取
        while (!feof($handle) && $sum_buffer < $filesize) {
            echo fread($handle, $read_buffer);
            $sum_buffer += $read_buffer;
        }
        //关闭句柄
        fclose($handle);
        exit;
    }


}
